#!/bin/bash

# WMS3D Development Startup Script
# 开发环境启动脚本

set -e

echo "🚀 WMS3D 开发环境启动"
echo "======================"

# Check if Docker is running
if ! docker info > /dev/null 2>&1; then
    echo "❌ Docker 未运行，请先启动 Docker"
    exit 1
fi

# Function to check if service is healthy
check_service() {
    local url=$1
    local service_name=$2
    local max_attempts=30
    local attempt=1
    
    echo "🔍 检查 $service_name 服务状态..."
    
    while [ $attempt -le $max_attempts ]; do
        if curl -s "$url" > /dev/null 2>&1; then
            echo "✅ $service_name 服务正常运行"
            return 0
        fi
        
        echo "⏳ 等待 $service_name 服务启动... ($attempt/$max_attempts)"
        sleep 2
        attempt=$((attempt + 1))
    done
    
    echo "❌ $service_name 服务启动失败"
    return 1
}

# Start services
echo "📦 启动服务..."
docker compose up -d

# Wait for services to be healthy
echo "⏳ 等待服务启动..."
sleep 10

# Check service health
check_service "http://localhost:9000/health" "主服务"
check_service "http://localhost:9000/sensor/health" "传感器网关"
check_service "http://localhost:9000/wms/health" "WMS核心"
check_service "http://localhost:9000/trajectory/health" "轨迹引擎"

# Initialize sample data
echo "📊 初始化示例数据..."
python -c "from src.wms3d.tests.initialize_sample_data import initialize_sample_data; import asyncio; asyncio.run(initialize_sample_data())"

# Run tests
echo "🧪 运行测试..."
python run_tests.py

echo ""
echo "🎉 启动完成！"
echo ""
echo "📋 服务地址:"
echo "   主服务: http://localhost:9000"
echo "   传感器网关: http://localhost:9000/sensor"
echo "   WMS核心: http://localhost:9000/wms"
echo "   轨迹引擎: http://localhost:9000/trajectory"
echo ""
echo "🧪 测试命令:"
echo "   python test_apis.py          # API测试"
echo "   python test_dify_simulation.py  # Dify节点模拟"
echo "   python run_tests.py          # 完整测试"
echo ""
echo "📚 API文档:"
echo "   传感器网关: http://localhost:9000/sensor/docs"
echo "   WMS核心: http://localhost:9000/wms/docs"
echo "   轨迹引擎: http://localhost:9000/trajectory/docs"